package com.heima.comment.service.impl;
import java.math.BigDecimal;
import java.util.*;

import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private GreenTextScan  greenTextScan;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MongoTemplate mongoTemplate;



    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        if (dto==null || dto.getCommentId()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (dto.getMinDate()==null)
            dto.setMinDate(new Date());
        int size = 20;
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()))
                        .with(Sort.by(Sort.Direction.DESC,"CreatedTime")).limit(size);
        List<ApCommentRepay> repayList = mongoTemplate.find(query, ApCommentRepay.class);
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null||user.getId()==null)
            return ResponseResult.okResult(repayList);
        List<String> repayIds = repayList.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
        Query repayLikesQuery = Query.query(Criteria.where("commentRepayId").in(repayIds).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> likes = mongoTemplate.find(repayLikesQuery, ApCommentRepayLike.class);
        if (likes.isEmpty())
            return ResponseResult.okResult(repayList);
        Set<String> set = likes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toSet());
        List<ApCommentRepayVo> list = repayList.stream().map(repay -> {
            ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
            BeanUtils.copyProperties(repay, apCommentRepayVo);
            if (set.contains(apCommentRepayVo.getId()))
                apCommentRepayVo.setOperation((short) 0);
            return apCommentRepayVo;
        }).collect(Collectors.toList());
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        if (dto==null||dto.getCommentId()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (StringUtils.isBlank(dto.getContent()) ||dto.getContent().length()>140)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null||user.getId()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        try {
            Map map = greenTextScan.greeTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            if ("block".equals(suggestion))
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"请谨言慎行");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApUser apuser = userFeign.findUserById(Long.valueOf(user.getId()));
        if (apuser==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"当前登陆信息有误");
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"评论不存在");
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apuser.getId());
        apCommentRepay.setAuthorName(apuser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        if (dto==null || dto.getCommentRepayId()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (dto.getOperation()==null || (dto.getOperation()!=0&&dto.getOperation()!=1))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null||user.getId()==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"不存在该回复");
        if (dto.getOperation()==0){
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short)0);
            mongoTemplate.save(apCommentRepayLike);
            apCommentRepay.setLikes(apCommentRepay.getLikes()+1);
            mongoTemplate.save(apCommentRepay);
        }else{
            Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
            mongoTemplate.remove(query);
            apCommentRepay.setLikes(apCommentRepay.getLikes()==0?0:apCommentRepay.getLikes()-1);
            mongoTemplate.save(apCommentRepay);
        }
        Map map = new HashMap();
        map.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(map);
    }
}
